from google.appengine.api import users
from django.shortcuts import HttpResponse, render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect, Http404
from whatyou.main.models import *
import datetime
import time

def get_or_create_person(user):
    """Gets or create person record"""
    if user:
        try:
            person = Person.all().filter("user =", user)[0]
        except IndexError:
            person = Person(user=user, friendly_name=user.nickname())
            person.put()
        if not person.registration_date:
            person.registration_date = datetime.datetime.today()
        return person
    else:
        return None

def get_or_create_verb(verb_input):
    verb_lower = verb_input.lower()
    try:
        verb = Verb.all().filter("name =", verb_lower)[0]
    except IndexError:
        verb = Verb(name=verb_input)
        verb.put()
    return verb

def respond(request, user, template, params=None):
    """Helper to render a response, passing standard stuff to the response."""
    if params is None:
        params = {}
    if user:
        person = get_or_create_person(user)
        params["user"] = user
        params["person"] = person
        params["logout_url"] = users.create_logout_url("/")
        params["is_admin"] =  users.is_current_user_admin()
    else:
        params["login_url"] = users.create_login_url("/")
    return render_to_response(template, params)
